extends Node2D


@onready var friend_container: VBoxContainer = $FriendContainer
@onready var invite_friends: Button = $InviteFriends
@onready var lobby: VBoxContainer = $Lobby

var friends = []
var online_friends = []
var avatar_requests = {} # 存储 {user_id: Image} 的映射关系


var _lobby_id: int = 0
var lobby_type: int = 2
var lobby_max_players: int = 2
var lobby_members: Array = []
var matchmaking_phase: int = 0
var find_lobbies: Array = []
var lobby_data: Dictionary = {
	"name": "songda"
}

func _ready() -> void:
	_load_friends()
	Steam.avatar_loaded.connect(_on_loaded_avatar)
	Steam.lobby_created.connect(_on_lobby_created)
	Steam.lobby_match_list.connect(_on_lobby_match_list)
	Steam.lobby_chat_update.connect(_on_lobby_chat_update)

func _process(delta: float) -> void:
	pass


func _load_friends() -> void:
	friends = Steam.getUserSteamFriends()
	online_friends = friends.filter(func(friend): return friend.get("status") != 0)
	for child in friend_container.get_children():
		child.queue_free()

	for friend in online_friends:
		var hbox = HBoxContainer.new() # 水平容器
		friend_container.add_child(hbox)
		
		# 添加头像（假设Steam提供头像获取方法）
		var avatar_rect = TextureRect.new()
		hbox.add_child(avatar_rect)
		avatar_rect.size = Vector2(32, 32)
		avatar_rect.modulate = Color(0.5, 0.5, 0.5) # 灰色占位
		# 记录user_id与TextureRect的映射
		avatar_requests[friend.id] = avatar_rect
		
		# 添加好友名称标签
		var name_label = Label.new()
		hbox.add_child(name_label)
		name_label.text = friend.name
		name_label.size_flags_horizontal = Control.SIZE_EXPAND_FILL # 水平填充
		name_label.size_flags_vertical = Control.SIZE_SHRINK_CENTER # 垂直居中
		name_label.autowrap_mode = TextServer.AUTOWRAP_WORD # 按单词换行
		name_label.custom_minimum_size = Vector2(200, 0) # 设置最小宽度为200，高度自适应
		
		# 添加邀请按钮
		var invite_btn = Button.new()
		hbox.add_child(invite_btn)
		invite_btn.text = "邀请"
		invite_btn.connect("pressed", Callable(self, "_on_invite_pressed").bind(friend.id))
		Steam.getPlayerAvatar(1, friend.id)

func _on_invite_pressed(id: int):
	Steam.inviteUserToLobby(_lobby_id, id)

func _on_invite_friends_pressed() -> void:
	# 显示/隐藏容器
	friend_container.visible = !friend_container.visible # Replace with function body.

func _on_loaded_avatar(user_id: int, avatar_size: int, avatar_buffer: PackedByteArray) -> void:
	print("Avatar for user: %s" % user_id)
	print("Size: %s" % avatar_size)

	# Create the image and texture for loading
	var avatar_image: Image = Image.create_from_data(avatar_size, avatar_size, false, Image.FORMAT_RGBA8, avatar_buffer)

	# Optionally resize the image if it is too large
	if avatar_size > 128:
		avatar_image.resize(128, 128, Image.INTERPOLATE_LANCZOS)

	# Apply the image to a texture
	var avatar_texture: ImageTexture = ImageTexture.create_from_image(avatar_image)
	avatar_requests[user_id].texture = avatar_texture


func _on_create_lobby_pressed() -> void:
	Steam.createLobby(lobby_type, lobby_max_players)


func _on_lobby_created(connect: int, lobby_id: int) -> void:
	print(connect)
	print(lobby_id)
	self._lobby_id = lobby_id
	Steam.setLobbyJoinable(lobby_id, true)
	Steam.setLobbyData(lobby_id, "name", "songda")
	_update_lobby_members()

func _on_search_lobbies_pressed() -> void:
	matchmaking_loop()
	
func matchmaking_loop() -> void:
	# If this matchmake_phase is 3 or less, keep going
	if matchmaking_phase < 4:
		###
		# Add other filters for things like game modes, etc.
		# Since this is an example, we cannot set game mode or text match features.
		# However you could use addRequestLobbyListStringFilter to look for specific
		# text in lobby metadata to match different criteria.
		###
		# Set the distance filter
		Steam.addRequestLobbyListDistanceFilter(matchmaking_phase)
		Steam.addRequestLobbyListStringFilter("name", "songda", Steam.LOBBY_COMPARISON_EQUAL)

		# Request a list
		Steam.requestLobbyList()

	else:
		print("[STEAM] Failed to automatically match you with a lobby. Please try again.")

func _on_lobby_match_list(lobbies: Array):
	find_lobbies = lobbies
	if find_lobbies.size() > 0:
		print("[STEAM] Found lobby!")
		_render_lobbies(find_lobbies)

	else:
		print("[STEAM] No lobbies found. Trying again...")
		matchmaking_phase += 1
		if matchmaking_phase < 4:
			matchmaking_loop()
		else:
			matchmaking_phase = 0

func _render_lobbies(lobbies: Array) -> void:
	"""
	渲染大厅列表到UI中，显示大厅名称并添加加入按钮。
	"""
	# 清理现有的大厅列表
	for child in lobby.get_children():
		child.queue_free()

	# 遍历找到的大厅，渲染每个大厅的信息
	for lobby_id in lobbies:
		var hbox = HBoxContainer.new() # 水平容器
		lobby.add_child(hbox)
		
		# 添加大厅名称标签
		var name_label = Label.new()
		hbox.add_child(name_label)
		name_label.text = Steam.getLobbyData(lobby_id, "name") # 获取大厅名称
		name_label.size_flags_horizontal = Control.SIZE_EXPAND_FILL # 水平填充
		name_label.size_flags_vertical = Control.SIZE_SHRINK_CENTER # 垂直居中
		name_label.autowrap_mode = TextServer.AUTOWRAP_WORD # 按单词换行
		name_label.custom_minimum_size = Vector2(200, 0) # 设置最小宽度为200，高度自适应
		
		# 添加加入按钮
		var join_btn = Button.new()
		hbox.add_child(join_btn)
		join_btn.text = "加入"
		join_btn.connect("pressed", Callable(self, "_on_join_lobby_pressed").bind(lobby_id))


func _on_join_lobby_pressed(lobby_id: int) -> void:
	"""
	当点击加入按钮时调用，请求加入对应的大厅。
	"""
	print("Attempting to join lobby: %s" % lobby_id)
	Steam.joinLobby(lobby_id)

func _on_lobby_chat_update(lobby_id: int, changed_id: int, making_changed_id: int, chat_state: int) -> void:
	_update_lobby_members()


func _update_lobby_members():
	var nums = Steam.getNumLobbyMembers(_lobby_id)
	lobby_members.clear()
	for i in range(nums):
		lobby_members.append(Steam.getLobbyMemberByIndex(_lobby_id, i))
	print(" [STEAM] Lobby members: %s" % lobby_members)
